package megrez.job.custom.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import megrez.job.common.Snowflake;

/**
 * 任务配置信息
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "job_config")
public class Config{
    @Id
    @EqualsAndHashCode.Include
    @Column(updatable = false, nullable = false, unique = true)
    private String id;

    @Version
    @Column(nullable = false)
    private Integer version;
    
    @CreatedBy
    @Column(updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModifiedDate;
        
    /** 类完整名称 */
    private String className;

    /** 方法名称 */
    private String methodName;

    /** 方法参数 */
    private String methodParams;

    /** cron表达式 */
    private String cronExpression;

    /** 备注 */
    private String remark;

    /** 启用 */
    private Boolean enabled;

    @ToString.Exclude
    @OneToMany(mappedBy = "config", cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
    private List<Log> logs = new ArrayList<>();

    public Config() {
    }

    public Config(String className, String methodName, String methodParams, String cronExpression, String remark) {
        this.className = className;
        this.methodName = methodName;
        this.methodParams = methodParams;
        this.cronExpression = cronExpression;
        this.remark = remark;
        this.enabled = true;
    }

    @PrePersist
    @PreUpdate
    public void preAction() {
        if (getId() == null) {
            setId(Snowflake.nextIdStr());
        }

        if (enabled == null) {
            enabled = true;
        }

    }

}
